<template>
  <div class="major-category-management">
    <h2>专业与分类管理</h2>

    <div class="management-container">
      <!-- 左侧专业管理 -->
      <div class="major-panel">
        <div class="panel-header">
          <span>专业管理</span>
          <el-button type="primary" size="small" @click="showAddMajorDialog">
            <el-icon><Plus /></el-icon>添加专业
          </el-button>
        </div>

        <el-table
            :data="majors"
            highlight-current-row
            @current-change="handleMajorSelect"
            style="width: 100%"
            v-loading="loadingMajors"
        >
          <el-table-column prop="majorId" label="ID" width="80" />
          <el-table-column prop="majorName" label="专业名称" />
          <el-table-column prop="description" label="描述">
            <template #default="{ row }">
              <div class="description-cell">{{ row.description || '无描述' }}</div>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120" align="center">
            <template #default="{ row }">
              <el-button
                  type="primary"
                  size="small"
                  circle
                  @click="showEditMajorDialog(row)"
              >
                <el-icon><Edit /></el-icon>
              </el-button>
              <el-button
                  type="danger"
                  size="small"
                  circle
                  @click="deleteMajor(row.majorId)"
              >
                <el-icon><Delete /></el-icon>
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 右侧分类管理 -->
      <div class="category-panel">
        <div class="panel-header">
          <span>分类管理 ({{ currentMajor ? currentMajor.majorName : '未选择专业' }})</span>
          <el-button
              type="primary"
              size="small"
              @click="showAddCategoryDialog"
              :disabled="!currentMajor"
          >
            <el-icon><Plus /></el-icon>添加分类
          </el-button>
        </div>

        <el-table
            :data="categories"
            style="width: 100%"
            v-loading="loadingCategories"
            :empty-text="currentMajor ? '该专业下暂无分类' : '请先选择专业'"
        >
          <el-table-column prop="categoryId" label="ID" width="80" />
          <el-table-column prop="categoryName" label="分类名称" />
          <el-table-column prop="description" label="描述">
            <template #default="{ row }">
              <div class="description-cell">{{ row.description || '无描述' }}</div>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120" align="center">
            <template #default="{ row }">
              <el-button
                  type="primary"
                  size="small"
                  circle
                  @click="showEditCategoryDialog(row)"
              >
                <el-icon><Edit /></el-icon>
              </el-button>
              <el-button
                  type="danger"
                  size="small"
                  circle
                  @click="deleteCategory(row.categoryId)"
              >
                <el-icon><Delete /></el-icon>
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <!-- 添加/编辑专业对话框 -->
    <el-dialog
        v-model="majorDialogVisible"
        :title="majorForm.majorId ? '编辑专业' : '添加专业'"
        width="500px"
    >
      <el-form
          ref="majorFormRef"
          :model="majorForm"
          :rules="majorRules"
          label-width="80px"
      >
        <el-form-item label="专业名称" prop="majorName">
          <el-input
              v-model="majorForm.majorName"
              placeholder="请输入专业名称"
          />
        </el-form-item>
        <el-form-item label="描述">
          <el-input
              v-model="majorForm.description"
              type="textarea"
              :rows="3"
              placeholder="请输入专业描述（可选）"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="majorDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitMajorForm">确定</el-button>
      </template>
    </el-dialog>

    <!-- 添加/编辑分类对话框 -->
    <el-dialog
        v-model="categoryDialogVisible"
        :title="categoryForm.categoryId ? '编辑分类' : '添加分类'"
        width="500px"
    >
      <el-form
          ref="categoryFormRef"
          :model="categoryForm"
          :rules="categoryRules"
          label-width="80px"
      >
        <el-form-item label="所属专业" prop="majorId">
          <el-select
              v-model="categoryForm.majorId"
              placeholder="请选择专业"
              style="width: 100%"
              :disabled="!!categoryForm.categoryId"
          >
            <el-option
                v-for="major in majors"
                :key="major.majorId"
                :label="major.majorName"
                :value="major.majorId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="分类名称" prop="categoryName">
          <el-input
              v-model="categoryForm.categoryName"
              placeholder="请输入分类名称"
          />
        </el-form-item>
        <el-form-item label="描述">
          <el-input
              v-model="categoryForm.description"
              type="textarea"
              :rows="3"
              placeholder="请输入分类描述（可选）"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="categoryDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitCategoryForm">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import axios from '@/api/server';
import { Plus, Delete, Edit } from '@element-plus/icons-vue'; // 添加Edit图标
import { computed } from 'vue';

// 专业数据
const majors = ref([]);
const currentMajor = ref(null);
const loadingMajors = ref(false);

// 分类数据
const categories = ref([]);
const loadingCategories = ref(false);

// 对话框控制
const majorDialogVisible = ref(false);
const categoryDialogVisible = ref(false);

// 专业表单
const majorForm = reactive({
  majorId: null,
  majorName: '',
  description: ''
});

// 分类表单
const categoryForm = reactive({
  categoryId: null,
  majorId: null, // 新增专业ID字段
  categoryName: '',
  description: ''
});

// 表单验证规则
const majorRules = {
  majorName: [
    { required: true, message: '请输入专业名称', trigger: 'blur' },
    { min: 2, max: 50, message: '专业名称长度在2到50个字符', trigger: 'blur' }
  ]
};

const categoryRules = {
  majorId: [
    { required: true, message: '请选择所属专业', trigger: 'change' }
  ],
  categoryName: [
    { required: true, message: '请输入分类名称', trigger: 'blur' },
    { min: 2, max: 50, message: '分类名称长度在2到50个字符', trigger: 'blur' }
  ]
};

// 初始化加载专业数据
onMounted(() => {
  fetchMajors();
});

// 获取专业列表
const fetchMajors = async () => {
  try {
    loadingMajors.value = true;
    const response = await axios.get('/admin/manage/majors');
    majors.value = response.data.data || [];

    // 默认选中第一个专业
    if (majors.value.length > 0) {
      currentMajor.value = majors.value[0];
      fetchCategoriesByMajor(majors.value[0].majorId);
    }
  } catch (error) {
    console.error('获取专业列表失败:', error);
    ElMessage.error('获取专业列表失败');
  } finally {
    loadingMajors.value = false;
  }
};

// 根据专业ID获取分类
const fetchCategoriesByMajor = async (majorId) => {
  try {
    loadingCategories.value = true;
    const response = await axios.get(`/admin/manage/categories/by-major/${majorId}`);
    categories.value = response.data.data || [];
  } catch (error) {
    console.error('获取分类列表失败:', error);
    ElMessage.error('获取分类列表失败');
  } finally {
    loadingCategories.value = false;
  }
};

// 选择专业
const handleMajorSelect = (major) => {
  if (major) {
    currentMajor.value = major;
    fetchCategoriesByMajor(major.majorId);
  }
};

// 显示添加专业对话框
const showAddMajorDialog = () => {
  majorForm.majorId = null;
  majorForm.majorName = '';
  majorForm.description = '';
  majorDialogVisible.value = true;

  // 清除表单验证
  nextTick(() => {
    if (majorFormRef.value) {
      majorFormRef.value.clearValidate();
    }
  });
};

// 显示编辑专业对话框
const showEditMajorDialog = (major) => {
  majorForm.majorId = major.majorId;
  majorForm.majorName = major.majorName;
  majorForm.description = major.description || '';
  majorDialogVisible.value = true;

  // 清除表单验证
  nextTick(() => {
    if (majorFormRef.value) {
      majorFormRef.value.clearValidate();
    }
  });
};

// 显示添加分类对话框
const showAddCategoryDialog = () => {
  categoryForm.categoryId = null;
  categoryForm.majorId = currentMajor.value?.majorId || null; // 默认选中当前专业
  categoryForm.categoryName = '';
  categoryForm.description = '';
  categoryDialogVisible.value = true;

  nextTick(() => {
    if (categoryFormRef.value) {
      categoryFormRef.value.clearValidate();
    }
  });
};

// 显示编辑分类对话框
const showEditCategoryDialog = (category) => {
  categoryForm.categoryId = category.categoryId;
  categoryForm.majorId = currentMajor.value?.majorId || null; // 默认选中当前专业
  categoryForm.categoryName = category.categoryName;
  categoryForm.description = category.description || '';
  categoryDialogVisible.value = true;

  nextTick(() => {
    if (categoryFormRef.value) {
      categoryFormRef.value.clearValidate();
    }
  });
};

// 提交专业表单
const submitMajorForm = async () => {
  try {
    // 表单验证
    if (!majorForm.majorName) {
      ElMessage.warning('请输入专业名称');
      return;
    }

    if (majorForm.majorId) {
      // 更新专业
      await axios.put(`/admin/manage/majors/${majorForm.majorId}`, majorForm);
      ElMessage.success('专业更新成功');
    } else {
      // 添加专业
      await axios.post('/admin/manage/majors', majorForm);
      ElMessage.success('专业添加成功');
    }

    majorDialogVisible.value = false;
    fetchMajors();
  } catch (error) {
    console.error('操作失败:', error);
    ElMessage.error(error.response?.data?.message || '操作失败');
  }
};

// 提交分类表单
const submitCategoryForm = async () => {
  try {
    // 表单验证
    if (!categoryForm.majorId) {
      ElMessage.warning('请选择所属专业');
      return;
    }
    if (!categoryForm.categoryName) {
      ElMessage.warning('请输入分类名称');
      return;
    }

    if (categoryForm.categoryId) {
      // 更新分类
      await axios.put(`/admin/manage/categories/${categoryForm.categoryId}`, categoryForm);
      ElMessage.success('分类更新成功');
    } else {
      // 添加分类
      await axios.post('/admin/manage/categories', categoryForm);
      ElMessage.success('分类添加成功');
    }

    categoryDialogVisible.value = false;

    // 根据操作后的专业ID刷新分类列表
    const refreshMajorId = categoryForm.majorId;
    fetchCategoriesByMajor(refreshMajorId);

    // 如果当前专业不是操作后的专业，需要更新当前专业显示
    if (currentMajor.value?.majorId !== refreshMajorId) {
      const newMajor = majors.value.find(m => m.majorId === refreshMajorId);
      if (newMajor) {
        currentMajor.value = newMajor;
      }
    }
  } catch (error) {
    console.error('操作失败:', error);
    ElMessage.error(error.response?.data?.message || '操作失败');
  }
};

// 删除专业
const deleteMajor = async (majorId) => {
  try {
    await ElMessageBox.confirm('确定删除该专业吗？该操作会同时删除其下所有分类', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
      dangerouslyUseHTMLString: true,
      customClass: 'delete-confirm-box'
    });

    await axios.delete(`/admin/manage/majors/${majorId}`);
    ElMessage.success('专业删除成功');
    fetchMajors();
  } catch (error) {
    if (error.response?.data?.message) {
      // 显示后端返回的具体错误信息
      ElMessage.error(error.response.data.message);
    } else if (error !== 'cancel') {
      ElMessage.error('删除失败');
    }
  }
};

// 删除分类
const deleteCategory = async (categoryId) => {
  try {
    await ElMessageBox.confirm('确定删除该分类吗？', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });

    await axios.delete(`/admin/manage/categories/${categoryId}`);
    ElMessage.success('分类删除成功');

    // 重新加载当前专业下的分类
    if (currentMajor.value) {
      fetchCategoriesByMajor(currentMajor.value.majorId);
    }
  } catch (error) {
    if (error.response?.data?.message) {
      // 显示后端返回的具体错误信息
      ElMessage.error(error.response.data.message);
    } else if (error !== 'cancel') {
      ElMessage.error('删除失败');
    }
  }
};

// 表单引用
const majorFormRef = ref(null);
const categoryFormRef = ref(null);
</script>

<style scoped>
.major-category-management {
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.management-container {
  display: flex;
  gap: 20px;
  margin-top: 20px;
}

.major-panel, .category-panel {
  flex: 1;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.panel-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 15px;
  background-color: #f5f7fa;
  border-bottom: 1px solid #ebeef5;
}

.panel-header span {
  font-weight: bold;
  color: #303133;
}

.description-cell {
  max-height: 60px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

:deep(.el-table) {
  flex: 1;
}

:deep(.el-table__empty-block) {
  min-height: 200px;
}

/* 操作按钮间距 */
:deep(.el-button + .el-button) {
  margin-left: 8px;
}
</style>